<!-- 采购管理-物料汇总列表 -->
<template>
  <pageHeader
    :title="title"
    :breadCrumb="breadCrumb"
    :ok-button-props="{ style: { display: 'none' } }"
  >
  </pageHeader>
  <div>
    <a-tabs @change="searchState" type="line" v-model="searchStateVal">
      <a-tab-pane :key="0" title="全部"> </a-tab-pane>
      <a-tab-pane :key="1" title="待处理"> </a-tab-pane>
      <a-tab-pane :key="2" title="处理中"> </a-tab-pane>
      <a-tab-pane :key="3" title="已完成"> </a-tab-pane>
    </a-tabs>
  </div>
  <div class="search-box">
    <a-space>
      <!-- <a-input-search
        @change="onChange"
        :style="{ width: 'auto' }"
        placeholder="请输入"
        v-model="currSelectSearch"
      >
        <template #prefix>
          <a-select
            :style="{ width: '120px', marginRight: '10px' }"
            placeholder="请选择"
            v-model="currSelectVal"
          >
            <a-option value="number">物料编号</a-option>
            <a-option value="name">物料名称</a-option>
            <a-option value="Dept"> 申请部门</a-option>
          </a-select>
        </template>
      </a-input-search> -->
      <a-input-group>
        <!-- <a-select
          :style="{ width: '120px' }"
          placeholder="请选择"
          v-model="currSelectVal"
        >
          <a-option value="number">产品编号</a-option>
        </a-select> -->
        <a-input-search
          :style="{ width: 'auto' }"
          placeholder="请输入产品编号"
          @search="search"
          v-model="currSelectSearch"
          search-button
        />
      </a-input-group>
      <a-button type="outline" @click="reset">
        <template #icon>
          <icon-refresh />
        </template>
        <template #default>重置</template>
      </a-button>
    </a-space>

    <a-space>
      <a-button status="success">
        <template #icon>
          <icon-download />
        </template>
        <template #default>导入</template>
      </a-button>

      <a-button status="warning">
        <template #icon>
          <icon-export :rotate="-90" />
        </template>
        <template #default>导出</template>
      </a-button>

      <a-button
        :disabled="createEnable"
        v-if="userState === 1"
        type="outline"
        @click="Datasummary"
        >数据汇总</a-button
      >
      <a-button type="primary" @click="showFormHeaderSetting"
        >表头设置</a-button
      >
    </a-space>
  </div>
  <div style="padding: 10px">
    <tableTurn
      :tableData="getData"
      :args="{
        rowSelection:
          userState === 1
            ? {
                type: 'checkbox',
              }
            : false,
      }"
      ref="tableRef"
    >
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.code"
        :title="item.name"
        :data-index="item.code"
        :width="150"
        align="center"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      >
        <template v-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
        </template>

        <template v-else-if="item.code === 'deliveryTime'" #cell="{ record }">
          {{
            record.deliveryTime
              ? dayjs(record.deliveryTime).format('YYYY-MM-DD')
              : '无'
          }}
        </template>

        <template v-else-if="item.code === 'priority'" #cell="{ record }">
          <a-typography-text
            v-if="record.priority === 1"
            style="color: #999999"
          >
            低
          </a-typography-text>
          <a-typography-text v-else-if="record.priority === 2" type="primary">
            中
          </a-typography-text>
          <a-typography-text v-else-if="record.priority === 3" type="warning">
            高
          </a-typography-text>
          <a-typography-text v-else-if="record.priority === 4" type="danger">
            紧急
          </a-typography-text>
          <a-typography-text v-else> - </a-typography-text>
        </template>

        <template
          v-else-if="item.code === 'applyByUserName'"
          #cell="{ record }"
        >
          {{ record.applyByUserName || '-' }}
        </template>

        <template v-else-if="item.code === 'state'" #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderStatus.filter((ele) => ele.id === record.state)[0]
                ?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{ orderStatus.filter((ele) => ele.id === record.state)[0]?.value }}
          </div>
        </template>
      </a-table-column>

      <a-table-column :width="100" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <a-tooltip v-if="record.state === 1" content="更多功能">
            <a-dropdown>
              <IconFont
                type="icon-more-def"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
              />
              <template #content>
                <a-doption>
                  <a-button type="text" @click="edit(record)"
                    >创建订单</a-button
                  ></a-doption
                >
                <!-- <a-doption disabled
                    ><a-button type="text">锁定</a-button></a-doption
                  > -->
                <a-doption :value="{ value: 'Option3' }"
                  ><a-button type="text" @click="addTast(record)"
                    >创建任务</a-button
                  ></a-doption
                >
              </template>
            </a-dropdown>
          </a-tooltip>

          <!-- <a-button
            v-if="record.state !== 1"
            type="text"
            @click="goDetails(record.id)"
            >查看</a-button
          > -->

          <a-tooltip v-if="record.state !== 1" content="查看详情">
            <IconFont
              type="icon-details-def"
              :size="30"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDetails(record.id)"
            />
          </a-tooltip>
        </template>
      </a-table-column>
    </tableTurn>
  </div>
  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="物料需求列表表头设置"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
  <!-- <AddOrder
    v-if="modelVisible"
    v-model:visible="modelVisible"
    :SeeDate="SeeDate"
  >
  </AddOrder>
  <AddTask
    v-model:visible="isTaskVisible"
    :tableData="taskTableData"
    v-if="taskTableData.length > 0"
    @addTaskEmit="addTaskEmit"
    ref="TaskRef"
  >
  </AddTask> -->
</template>

<script lang="ts" setup>
  import {
    reactive,
    ref,
    computed,
    onMounted,
    defineAsyncComponent,
    watchEffect,
    nextTick,
    unref,
  } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    getPurchaseHeader,
    PUTPurchaseHeader,
    getPurchaseProductList,
  } from '@/api/buy-management/buy-material/index';
  import { postPurchasetaskList } from '@/api/buy-management/buy-task/index';
  import miiter from '@/utils/mitt';
  import { isArray } from 'lodash';
  import { useBuyStore } from '@/store';
  import { getPurchaseProductNumber } from '@/api/buy-management/buy-material/index';
  import { install$3 } from 'echarts/types/dist/shared';
  // import AddOrder from './add-order/index.vue';

  onMounted(() => {});
  let AddTask = defineAsyncComponent(() => import('./add-task/index.vue'));
  // 表格配置
  const store = useBuyStore();
  const args = reactive({
    stripe: false,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'id', // 批量选择按钮 以合同名称来作为key
  });
  const searchStateVal = ref(0);
  const router = useRouter();
  const title: string = '物料需求列表';
  const breadCrumb: string[] = ['采购管理', '采购管理', '物料需求列表'];
  const modelVisible = ref(false);
  const isTaskVisible = ref(false);
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  const modelCauseVisible = ref(false);
  const createEnable = ref(true);
  const userState = ref();
  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive<any>({
    list: [],
  });

  miiter.on('selectedDis', (val: any) => {
    createEnable.value = val;
  });

  // <a-typography-text v-if="record.state === 1" style="color: #999999">
  //           待处理
  //         </a-typography-text>
  //         <a-typography-text v-if="record.state === 2" type="primary">
  //           处理中
  //         </a-typography-text>
  //         <a-typography-text v-if="record.state === 3" type="success">
  //           已完成
  //         </a-typography-text>
  const orderStatus = [
    { id: 1, value: '待处理', backgroundColor: '#cccccc' },
    { id: 2, value: '处理中', backgroundColor: '#4e8bfb' },
    { id: 3, value: '已完成', backgroundColor: '#009933' },
  ];

  // eslint-disable-next-line no-unused-expressions

  const getData = async (page: any) => {
    try {
      const msg: any = {};
      if (currSelectSearch.value) msg.number = currSelectSearch.value;
      if (userState.value) msg.state = userState.value;
      if (priorityData.value) msg.priority = priorityData.value;
      const res = await getPurchaseProductList({
        ...page,
        ...msg,
      });
      if (res.content === null || res.content === undefined) {
        res.content = [];
      }
      res.content.map((item: any) => {
        item.show = false;
        return item;
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };
  const header = [
    { code: 'number', isDefault: 1, name: '产品编号' },
    { code: 'name', isDefault: 1, name: '产品名称' },
    { code: 'priority', isDefault: 1, name: '优先级' },
    { code: 'materialName', isDefault: 1, name: '采购类别' },
    { code: 'spec', isDefault: 1, name: '规格型号' },
    { code: 'basicName', isDefault: 1, name: '基本单位' },
    { code: 'amount', isDefault: 1, name: '产品数量' },
    { code: 'deliveryTime', isDefault: 1, name: '需求交付日期' },
    { code: 'applyByUserName', isDefault: 1, name: '申请人' },
    { code: 'createdAt', isDefault: 1, name: '申请日期' },
    { code: 'state', isDefault: 1, name: '状态' },
  ];

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };
  // 获取表头数据
  const headerSettingData = async () => {
    try {
      const res = await getPurchaseHeader({ userId: 317, listType: 2 });
      headerSetting.list = res.extends ? res.extends : header;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    headerSetting.list.forEach((item: any) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  const searchState = (key: any) => {
    userState.value = key;
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
    tableRef.value.selectedList = [];
    tableRef.value.selectedKeys = [];
    tableRef.value.isDisabled = true;
    createEnable.value = true;
  };

  // 重置按钮
  const reset = () => {
    currSelectVal.value = '';
    currSelectSearch.value = '';
    userState.value = undefined;
    priorityData.value = undefined;
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const search = () => {
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const headerSave = async (val: any) => {
    try {
      const data = {
        userId: 317,
        listType: 2,
        extend: JSON.stringify(val),
      };
      await PUTPurchaseHeader(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const SeeDate: any = ref([]);

  const edit = async (item: any) => {
    item.sourceProductId = item.id;
    item.sid = `${item.id}`;
    // record.sourceProductId = record.id;
    // record.sid = `${record.id}`;
    store.CreateOrder = {
      Product: [{ ...item }],
    };
    router.push({
      name: 'AddOrderPurchaseList',
    });
  };

  const Datasummary = () => {
    store.collect = tableRef.value.selectedList;
    router.push({
      name: 'MaterialSummary',
    });
  };

  const goDetails = (id: number) => {
    router.push({
      name: 'MaterialDetails',
      query: { id },
    });
  };
  const TaskRef = ref();
  const taskTableData: any = ref([]);
  const addTast = (record: any) => {
    taskTableData.value[0] = { ...record };
    isTaskVisible.value = true;
    TaskRef.value.refresh();
  };

  const addTaskEmit = async (form: any, product: any) => {
    try {
      product.forEach((item: any) => {
        item.planAmount = item.amount;
      });
      await postPurchasetaskList({ ...form, taskProduct: product });
      reset();
      taskTableData.value = [];
    } catch (err: unknown) {
      console.log(err);
    }
  };
</script>

<style scoped lang="less">
  // .content-head {
  // }
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
  }
  :deep(.arco-space-item) {
    margin-top: 10px;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
</style>
